﻿using Confluent.Kafka;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.Elasticsearch;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo.Net.Serilog
{
    public static class SerilogExtensions
    {

        public static IServiceCollection AddSerilogClient(this IServiceCollection services, IConfiguration configuration)
        {

            //配置serilog
            services.AddLogging(option =>
            {
                option.ClearProviders();  //移除原有的日志服务
                option.AddSerilog();// 注册 Serilog
            }
            );
            return services;
        }


        public static IServiceCollection AddSerilogFileClient(this IServiceCollection services, IConfiguration configuration)
        {

            Log.Logger = new LoggerConfiguration()  
            .WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day)  //存到 文件
            .CreateLogger();

            //配置serilog
            services.AddLogging(option =>
            {
              //  option.ClearProviders();  //移除原有的日志服务
                option.AddSerilog();// 注册 Serilog
            });
            return services;
        }



        public static IServiceCollection AddSerilogEsClient(this IServiceCollection services, IConfiguration configuration)
        {
            string esUri = configuration["ElasticSearchUri"];
            Log.Logger = new LoggerConfiguration().WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(esUri))
            {    IndexFormat = configuration["EsLogIndex"],  AutoRegisterTemplate = true })
             .MinimumLevel.Information() // 设置全局最小日志级别为Information
              .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // 对Microsoft前缀的源只记录Warning及以上级别的日志
              .MinimumLevel.Override("System", LogEventLevel.Warning) // 对System前缀的源只记录Warning及以上级别的日志
            .CreateLogger();
            //配置serilog
            services.AddLogging(option =>
            {
               option.ClearProviders();  //移除原有的日志服务
                option.AddSerilog();// 注册 Serilog
            });
            return services;
        }


        public static IServiceCollection AddSerilogPgSqlClient(this IServiceCollection services, IConfiguration configuration)
        {
            Log.Logger = new LoggerConfiguration().WriteTo.PostgreSQL(
                connectionString: configuration["PgSqlLog:ConnectionString"],tableName: configuration["PgSqlLog:TableName"], needAutoCreateTable: true)
                 .CreateLogger();

            //配置serilog
            services.AddLogging(option =>
            {
                option.ClearProviders();  //移除原有的日志服务
                option.AddSerilog();// 注册 Serilog
            });

            return services;
        }


    }
}
